﻿using BL;
using BL.Models.Account;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace UIServices.Accounts
{
    internal class FormsAuthenticationLogin : ILogin<User>
    {
        public void Login(User user, bool stayConnected)
        {
            HttpCookie logginCookie = FormsAuthentication.GetAuthCookie(user.ID.ToString(), stayConnected);

            HttpContext.Current.Response.Cookies.Add(logginCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }


        private User sessionUser
        {
            get
            {
                return HttpContext.Current.Session["currentLoggedUser"] as User;
            }
            set
            {
                HttpContext.Current.Session["currentLoggedUser"] = value;
            }
        }

        public User GetLoggedUser()
        {
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    try
                    {
                        int userId = int.Parse(FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name);

                        if (sessionUser == null || sessionUser.ID != userId)
                        {
                            sessionUser = User.GetByID(userId);
                        }

                        return sessionUser;
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return null;
        }

    }
}